package pl.register.android;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.WindowManager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockFragmentActivity;
import pl.register.android.activities.correlation.CorrelationFragment;
import pl.register.android.activities.program.ProgramFragment;
import pl.register.android.activities.students.StudentsFragment;
import pl.register.android.activities.tasks.TasksActivity;
import pl.register.android.activities.tasks.builders.TaskEditorDialogBuilder;
import pl.register.android.database.DatabaseAdapter;
import pl.register.android.database.dao.TaskDao;
import pl.register.android.task.Task;

public class HomeActivity extends RoboSherlockFragmentActivity {
    private static String TAG = "course-register";

    private static String CORRElATION_TAB_TAG = "correlation_tab_tag";

    private static String PROGRAM_TAB_TAG = "program_tab_tag";

    private static String STUDENTS_TAB_TAG = "students_tab_tag";

    private static String SELECTED_TAB_KEY = "selected_tab_key";

    private DatabaseAdapter databaseAdapter;

    private TaskDao taskDao;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        databaseAdapter = new DatabaseAdapter(this);
        databaseAdapter.open();
        taskDao = databaseAdapter.getTaskDao();

        onCreateTabs();

        if (savedInstanceState != null) {
            getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(SELECTED_TAB_KEY, 0));
        }
    }

    private void onCreateTabs() {
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        actionBar.addTab(actionBar
                .newTab()
                .setText(R.string.lbl_correlation)
                .setTabListener(new TabListener<CorrelationFragment>(this, CORRElATION_TAB_TAG, CorrelationFragment.class)));
        actionBar.addTab(actionBar
                .newTab()
                .setText(R.string.lbl_program)
                .setTabListener(new TabListener<ProgramFragment>(this, PROGRAM_TAB_TAG, ProgramFragment.class)));
        actionBar.addTab(actionBar
                .newTab()
                .setText(R.string.lbl_students)
                .setTabListener(new TabListener<StudentsFragment>(this, STUDENTS_TAB_TAG, StudentsFragment.class)));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getSupportMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_tasks:
                startActivity(new Intent(this, TasksActivity.class));
                return true;
            case R.id.menu_tasks_add:
                showTaskEditorDialog(Task.nullObject());
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showTaskEditorDialog(final Task task) {
        final TaskEditorDialogBuilder taskEditorBuilder = new TaskEditorDialogBuilder(this, task);
        taskEditorBuilder.setNegativeButton(R.string.btn_name_cancel, null);
        taskEditorBuilder.setPositiveButton(R.string.btn_name_save, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                taskEditorBuilder.getValuesFromFields(task);
                taskDao.save(task);
            }
        });
        taskEditorBuilder.create().show();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_TAB_KEY, getSupportActionBar().getSelectedNavigationIndex());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseAdapter != null) {
            databaseAdapter.close();
        }
    }

    public DatabaseAdapter getDatabaseAdapter() {
        return databaseAdapter;
    }

    public class TabListener<T extends SherlockFragment> implements ActionBar.TabListener {
        private SherlockFragment mFragment;
        private final SherlockFragmentActivity mActivity;
        private final String mTag;
        private final Class<T> mClass;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            mActivity = (SherlockFragmentActivity) activity;
            mTag = tag;
            mClass = clz;
        }

        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            // Check if the fragment has already been initialised
            SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null) {
                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            } else if (preInitializedFragment != null) {
                mFragment = preInitializedFragment;
                ft.attach(mFragment);
            } else {
                // Not found, so instantiate and add it to the activity
                mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            }
        }

        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }
    }

}